﻿' ----------------------------------------------------------------------------------
' Microsoft Developer & Platform Evangelism
' 
' Copyright (c) Microsoft Corporation. All rights reserved.
' 
' THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, 
' EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES 
' OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE.
' ----------------------------------------------------------------------------------
' The example companies, organizations, products, domain names,
' e-mail addresses, logos, people, places, and events depicted
' herein are fictitious.  No association with any real company,
' organization, product, domain name, email address, logo, person,
' places, or events is intended or should be inferred.
' ----------------------------------------------------------------------------------

Imports System.Data.Services.Client
Imports System.Globalization
Imports System.Windows.Threading
Imports Microsoft.Samples.WindowsPhoneCloud.Phone.Models
Imports Microsoft.Samples.WindowsPhoneCloud.StorageClient

Namespace ViewModel

    Public Class SqlSampleDataPageViewModel
        Inherits PivotItemViewModel
        Private Const IconsRootUri As String = "/Toolkit.Content/"
        Private Const SqlSampleDataEntityName As String = "SqlSampleData"

        Private ReadOnly dispatcher As Dispatcher

        Private isListing_Renamed As Boolean = False
        Private hasResults_Renamed As Boolean = True
        Private message_Renamed As String = String.Empty

        Public Sub New()
            Me.New(Deployment.Current.Dispatcher, App.CloudClientFactory.ResolveOdataServiceContext())
        End Sub

        Public Sub New(ByVal dispatcher As Dispatcher, ByVal odataServiceContext As DataServiceContext)
            Me.dispatcher = dispatcher
            Me.Context = odataServiceContext
            Me.Items = New DataServiceCollection(Of SqlSampleData)(odataServiceContext)
            AddHandler Me.Items.LoadCompleted, AddressOf OnLoadCompleted
        End Sub

        Public Property Items() As DataServiceCollection(Of SqlSampleData)

        Private privateContext As DataServiceContext
        Public Property Context() As DataServiceContext
            Get
                Return privateContext
            End Get
            Private Set(ByVal value As DataServiceContext)
                privateContext = value
            End Set
        End Property

        Public Property IsListing() As Boolean
            Get
                Return Me.isListing_Renamed
            End Get

            Set(ByVal value As Boolean)
                If Me.isListing_Renamed <> value Then
                    Me.isListing_Renamed = value
                    Me.NotifyPropertyChanged("IsListing")
                End If
            End Set
        End Property

        Public Property Message() As String
            Get
                Return Me.message_Renamed
            End Get

            Set(ByVal value As String)
                If Me.message_Renamed <> value Then
                    Me.message_Renamed = value
                    Me.NotifyPropertyChanged("Message")
                End If
            End Set
        End Property

        Public Property HasResults() As Boolean
            Get
                Return Me.hasResults_Renamed
            End Get

            Set(ByVal value As Boolean)
                If Me.hasResults_Renamed <> value Then
                    Me.hasResults_Renamed = value
                    Me.NotifyPropertyChanged("HasResults")
                End If
            End Set
        End Property

        Public Sub LoadSqlSampleData()
            If (Not Me.IsListing) Then
                ' Adding an incremental seed to avoid a cached response.
                Dim tableUri = New Uri(String.Format(CultureInfo.InvariantCulture, "{0}/{1}?incrementalSeed={2}", Me.Context.BaseUri, SqlSampleDataEntityName, DateTime.UtcNow.Ticks), UriKind.Absolute)

                Me.IsListing = True
                Me.Message = "Loading..."

                Try
                    Me.Items.Clear()
                    Me.Items.LoadAsync(tableUri)
                Catch exception As Exception
                    Dim errorMessage = StorageClientExceptionParser.ParseDataServiceException(exception).Message

                    Me.IsListing = False
                    Me.Message = String.Format(CultureInfo.InvariantCulture, "Error: {0}", errorMessage)
                End Try
            End If
        End Sub

        Protected Overrides Sub PopulateApplicationBarButtons(ByVal applicationBar As IApplicationBar)
            Dim refreshButton = New ApplicationBarIconButton(New Uri(String.Format(CultureInfo.InvariantCulture, "{0}{1}", IconsRootUri, "appbar.refresh.rest.png"), UriKind.Relative)) With {.Text = "refresh"}
            AddHandler refreshButton.Click, Sub(s, e) Me.LoadSqlSampleData()

            applicationBar.Buttons.Add(refreshButton)
        End Sub

        Protected Overridable Sub OnLoadCompleted(ByVal sender As Object, ByVal e As LoadCompletedEventArgs)
            If e.Cancelled Then
                Me.DispatchResult("The operation has been cancelled.")
            ElseIf e.Error IsNot Nothing Then
                Dim errorMessage = StorageClientExceptionParser.ParseDataServiceException(e.Error).Message
                Me.DispatchResult(String.Format(CultureInfo.InvariantCulture, "Error: {0}", errorMessage))
            ElseIf Me.Items.Continuation IsNot Nothing Then
                Try
                    Me.Items.LoadNextPartialSetAsync()
                Catch exception As Exception
                    Dim errorMessage = StorageClientExceptionParser.ParseDataServiceException(exception).Message

                    Me.IsListing = False
                    Me.Message = String.Format(CultureInfo.InvariantCulture, "Error: {0}", errorMessage)
                End Try
            Else
                Me.DispatchResult()
            End If
        End Sub

        Protected Overridable Sub DispatchResult(Optional ByVal message As String = "")
            Me.dispatcher.BeginInvoke(Sub()
                                          Me.Message = message
                                          Me.IsListing = False
                                      End Sub)
        End Sub
    End Class
End Namespace